
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { messages, deepCopy } from "share/common"
import { SelectDepOrPerson } from 'components/index';
import { Table, Button, Popover, Icon, Popconfirm, message, Tag, Modal } from 'antd'

import moment from 'moment'
import SearchArea from 'components/search-area'
import SlideFrame from 'components/slide-frame'
import NewFinanceRole from 'containers/setting/role-setting/finance-role/new-finance-role'
import RSService from 'containers/setting/role-setting/role-setting.service'
import 'styles/setting/role-setting/finance-role/finance-role.scss'
import 'styles/enterprise-manage/person-manage/person-manage.scss'
import ResizeTable from "components/resize-table";

class RoleSettingFinance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      searchForm: [
        {type: 'input', id: 'roleID', label: messages('setting.key935'/*角色编号*/)},
        {type: 'input', id: 'roleName', label: messages('setting.key936'/*角色名称*/)},
        {type: 'input', id: 'userName', label: messages('setting.key947'/*员工姓名*/)},
        {type: 'input', id: 'employee', label: messages('setting.key900'/*工号*/)},
        {type: 'list', id: 'corporationEntityOIDs', label: messages('setting.key944'/*法人实体*/),
          listType: 'corporation_entity_all', options: [], labelKey: 'companyName', valueKey: 'companyReceiptedOID'},
        {type: 'items', id: 'createDateRange', items: [
          {type: 'date', id: 'createStartDate', label: messages('setting.key948'/*创建日期从*/)},
          {type: 'date', id: 'createEndDate', label: messages('setting.key949'/*创建日期至*/)}
        ]},
        {type: 'items', id: 'modifyDateRange', items: [
          {type: 'date', id: 'modifyStartDate', label: messages('setting.key950'/*修改日期从*/)},
          {type: 'date', id: 'modifyEndDate', label: messages('setting.key951'/*修改日期至*/)}
        ]},
      ],
      searchParams: {},
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: 48, render: (value, record, index) =>
          this.state.pageSize * this.state.page + index + 1},
        {title: messages('setting.key935'/*角色编号*/), dataIndex: 'roleID'},
        {title: messages('setting.key936'/*角色名称*/), dataIndex: 'roleName'},
        {title: messages('setting.key937'/*角色说明*/), dataIndex: 'roleDescription', render: value => (
          value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
        )},
        {title: messages('setting.key938'/*创建日期*/), dataIndex: 'createdDate', width: '15%', render: value =>
          moment(value).format('YYYY-MM-DD hh:mm:ss')},
        {title: messages('setting.key952'/*修改日期*/), dataIndex: 'lastModifyDate', width: '15%', render: value =>
          moment(value).format('YYYY-MM-DD hh:mm:ss')},
        {title: messages('common.operation'), dataIndex: 'roleOID', width: '10%', render: (value, record) => {
          return (
            <div>
              <a onClick={() => {this.handleRowClick(record)}}>{messages('common.detail')}</a>
              <span className="ant-divider"/>
              {record.roleID !== 'SuperAud' && record.roleID !== 'SuperFin' ? (
                <Popconfirm onConfirm={() => this.handleDelete(value)} title={messages('common.confirm.delete')}>
                  <a onClick={e => {e.preventDefault();e.stopPropagation()}}>{messages('common.delete')}</a>
                </Popconfirm>
              ) : '-'}
            </div>
          )
        }},
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      slideFrameVisible: false,
      slideFrameParams: {},
      extraDep: {
        res: [],
        title: messages("common.please.select"),
        depClassName: "f-right select-dep-close-wrap",
        className: ["f-right select-dep-close-wrap", "f-right select-dep-close-wrap select-dep-close-wrap-show"]
      },
      roleSetting: menuRoute.getRouteItem('role-setting'),
      roleDetail: menuRoute.getRouteItem('role-setting-finance-detail') //角色详情页
    };
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    const { page, pageSize, searchParams } = this.state;
    this.setState({ loading: true });
    RSService.getFinanceRoleList(page, pageSize, searchParams).then(res => {
      this.setState({
        loading: false,
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
  };

  search = (result) => {
    let searchParams = this.state.searchParams;
    searchParams.departmentOIDs && searchParams.departmentOIDs.length && (result.departmentOIDs = searchParams.departmentOIDs);
    result.createStartDate && (result.createStartDate = moment(result.createStartDate).format('YYYY-MM-DD 00:00:00'));
    result.createEndDate && (result.createEndDate = moment(result.createEndDate).format('YYYY-MM-DD 23:59:59'));
    result.modifyStartDate && (result.modifyStartDate = moment(result.modifyStartDate).format('YYYY-MM-DD 00:00:00'));
    result.modifyEndDate && (result.modifyEndDate = moment(result.modifyEndDate).format('YYYY-MM-DD 23:59:59'));
    this.setState({
      searchParams: result,
      page: 0,
      pagination: {
        total: 0
      }
    }, ()=>{
      this.getList();
    })
  };

  //清除
  clear = () => {
    this.onCloseDepTag();
    this.search({})
  };

  //删除
  handleDelete = (roleOID) => {
    RSService.getAssignUsers(roleOID).then(response => {
      if (response.data && response.data.length) {
        Modal.info({
          title: messages('setting.key953'/*该角色不能删除*/), //该角色不能删除
          content: messages('setting.key954'/*该角色已分配了用户，如要删除该角色，请先移除内部员工*/), //该角色已分配了用户，如要删除该角色，请先移除内部员工
        })
      } else {
        RSService.deleteFinanceRole(roleOID).then(res => {
          if (res.data) {
            message.success(messages('common.delete.success', {name: ''}));
            this.getList()
          }
        })
      }
    })
  };

  //渲染已经选择的部门
  renderButtonTitle(titleArr) {
    if (titleArr.length < 1) {
      return messages("common.please.select");
    }
    let node = [];
    titleArr.map((item, i) => {
      node.push(<Tag key={i}>{item.name}</Tag>);
    });
    return node;
  }

  //search-area 选择部门
  selectDepSearchArea = (values) => {
    let extraDep = this.state.extraDep;
    let searchParams = this.state.searchParams;
    let deps = [];
    extraDep.res = values;
    if (extraDep.res.length > 0) {
      extraDep.depClassName = extraDep.className[1];
    } else {
      extraDep.depClassName = extraDep.className[0];
    }
    for (let i = 0; i < extraDep.res.length; i++) {
      deps.push(extraDep.res[i].departmentOID);
    }
    searchParams.departmentOIDs = deps;
    extraDep.title = this.renderButtonTitle(extraDep.res);
    this.setState({
      extraDep,
      searchParams
    })
  };

  //清除已经选择的部门
  onCloseDepTag = () => {
    this.selectDepSearchArea([])
  };

  handleRowClick = (record) => {
    this.context.router.push(this.state.roleDetail.url.replace(':roleOID', record.roleOID))
  };

  //返回
  goBack = () => {
    this.context.router.push(this.state.roleSetting.url)
  };

  render() {
    const { loading, searchForm, pagination, columns, data, slideFrameVisible, slideFrameParams, extraDep } = this.state;
    return (
      <div className="setting-role-setting-finance">
        <SearchArea searchForm={searchForm}
                    maxLength={2}
                    extraFields={
                      [
                        <div>
                          <div className="select-dep-search-area-title">{messages('setting.key902'/*部门*/)}:</div>
                          <div className="select-dep-search-area">
                            <div className="f-left select-dep-wrap">
                              <SelectDepOrPerson
                                renderButton={false}
                                title={extraDep.title}
                                onlyDep={true}
                                onConfirm={this.selectDepSearchArea}/>
                            </div>
                            <div className={extraDep.depClassName}
                                 onClick={this.onCloseDepTag}>
                              <Icon type="close-circle" className="closeCircle"/>
                            </div>
                          </div>
                        </div>
                      ]
                    }
                    submitHandle={this.search}
                    clearHandle={this.clear}
        />
        <div className="table-header">
          <div className="table-header-buttons">
            <Button type="primary"
                    onClick={() => {this.setState({slideFrameVisible: true, slideFrameParams: {hasInit: false}})}}>
              {messages('setting.key955'/*新建角色*/)}
            </Button>
          </div>
          <div className="table-header-title">{messages('common.total', {total: pagination.total})}</div>
        </div>
        <ResizeTable
          rowKey="roleOID"
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          size="middle"
          bordered
        />
        <a className="back" onClick={this.goBack}>
          <Icon type="rollback" style={{marginRight: 5}}/>
          {messages('common.back')}
        </a>
        <SlideFrame show={slideFrameVisible}
                    title={messages('setting.key955'/*新建角色*/)}
                    content={NewFinanceRole}
                    params={slideFrameParams}
                    onClose={() => {this.setState({slideFrameVisible: false})}}
        />
      </div>
    )
  }
}
RoleSettingFinance.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(RoleSettingFinance);
